<template>
  <q-page class="bg-grey-3">
    <div v-if="!error && Object.keys(detail).length > 0" class="q-pb-lg">
      <q-page-sticky position="top" expand class="flex justify-between q-pa-sm" style="z-index: 99;">
        <q-btn icon="arrow_back_ios" dense unelevated color="grey-8" @click="$router.back()" />
        <q-btn icon="shopping_cart" dense unelevated color="grey-8" to="/shop/order">
          <q-badge color="orange" floating v-if="totalAmount > 0">{{ totalAmount }}</q-badge>
        </q-btn>
      </q-page-sticky>

      <!-- 图片 -->
      <q-carousel
        v-model="slide"
        transition-prev="slide-right"
        transition-next="slide-left"
        swipeable
        animated
        control-type="unelevated"
        control-color="grey-8"
        control-text-color="white"
        padding
        arrows
        :thumbnails="detail.images.length > 1"
        style="height: 100vw;"
      >
        <q-carousel-slide :name="item.batch" :img-src="item.image" v-for="(item, index) in detail.images" :key="index" />
      </q-carousel>
      <!-- <q-img :src="detail.images[0].image" ratio="1" style="width: 100%; height: 100vw;" /> -->

      <!-- 品名规格 -->
      <div class="q-px-md q-pt-md">
        <q-card flat style="border-radius: 15px;">
          <q-card-section>
            <div class="flex justify-between">
              <div class="text-bold text-pink" style="font-size: 14px; line-height: normal;">¥<a style="font-size:28px;">{{ splitMoney(detail.sale_price)[0] }}</a>{{ splitMoney(detail.sale_price)[1] }}</div>
              <div class="text-grey-8" style="font-size: 12px">人气{{ detail.pv }}</div>
            </div>
            <div style="font-size: 18px; font-weight: bold;">{{ detail.material_name }}</div>
            <div class="text-grey-8">规格 {{ detail.material_model }}</div>
          </q-card-section>
        </q-card>
      </div>

      <!-- 可选规格 -->
      <div class="q-px-md q-pt-md">
        <q-card flat style="border-radius: 15px;">
          <q-card-section style="font-size: 18px;" class="text-bold">可选规格</q-card-section>
          <q-card-section>
            <q-btn-toggle
              v-model="modelUid"
              unelevated
              toggle-color="primary"
              :options="detail.otherModels.map(v => ({ label: v.material_model, value: v.uid }))"
              style="flex-wrap: wrap!important"
            />
          </q-card-section>
        </q-card>
      </div>

      <!-- 商品参数 -->
      <div class="q-px-md q-pt-md">
        <q-card flat style="border-radius: 15px;">
          <q-card-section style="font-size: 18px;" class="text-bold">商品参数</q-card-section>
          <q-card-section>
            <q-list bordered separator dense style="border-radius: 10px;">
              <q-item style="padding-left: 2px;" v-for="(item, index) in other" :key="index">
                <q-item-section class="text-grey-8 bg-grey-2 q-pl-sm">{{ item.label }}</q-item-section>
                <q-item-section class="q-pl-sm">{{ detail[item.field] }}</q-item-section>
              </q-item>
            </q-list>
          </q-card-section>
        </q-card>
      </div>

      <!-- 商品详情 -->
      <div class="q-px-md q-pt-md">
        <q-card flat style="border-radius: 15px;">
          <q-card-section style="font-size: 18px;" class="text-bold">商品详情</q-card-section>
          <q-card-section>
            <div v-html="detail.describe"></div>
          </q-card-section>
        </q-card>
      </div>

      <!-- 底栏 -->
      <q-footer bordered class="bg-white text-dark" >
        <q-toolbar>
          <div class="q-mr-md">
            <q-avatar size="42px" rounded @click="showCart">
              <img src="/images/cart.svg" />
              <q-badge color="orange" floating v-if="totalAmount > 0">{{ totalAmount }}</q-badge>
            </q-avatar>
          </div>

          <q-btn color="orange-4" class="full-width" size="16px" rounded unelevated text-color="black" label="加入购物车" @click="addCart" />
        </q-toolbar>
      </q-footer>

      <cartDialog ref="cartDialog" @update="updateCarts" />
    </div>
    <!-- 等候时的骨架 -->
    <div v-else-if="!error">
      <q-skeleton height="150px" square />

      <q-card-section>
        <q-skeleton type="text" class="text-subtitle1" />
        <q-skeleton type="text" width="50%" class="text-subtitle1" />
        <q-skeleton type="text" class="text-caption" />
      </q-card-section>
    </div>
    <!-- 错误信息 -->
    <div v-else-if="error" class="text-h4 text-center">
      {{ error }}
    </div>
  </q-page>
</template>

<script>
import { defineComponent } from 'vue';
import cartDialog from './components/cartDialog.vue';

export default defineComponent({
  name: 'shopDetail',
  components: { cartDialog },
  data () {
    return {
      id: '',
      detail: {},
      error: null,

      slide: '',
      other: [
        { field: 'material_unit', label: '计量单位' },
        { field: 'material', label: '材质/色号' },
        { field: 'brand', label: '品牌' },
        { field: 'origin', label: '产地' },
        { field: 'barcode', label: '条形编码' }
      ],

      carts: [],
      modelUid: ''
    };
  },
  mounted () {
    this.id = this.$route.params.id;
    this.refresh();
  },
  methods: {
    refresh () {
      this.$axios.get('/c/shop/detail', { params: { id: this.id } }).then(({ data }) => {
        if (data.result === 'fail') {
          this.$q.notify({
            message: data.message || '请求失败',
            color: 'negative',
            icon: 'error',
            position: 'center',
            timeout: 2000
          });
          this.error = data.message;
        } else {
          this.detail = data;
          this.slide = data.images[0].batch;
          this.modelUid = data.uid;

          if (this.$q.localStorage.has(this.cartId)) {
            this.carts = this.$q.localStorage.getItem(this.cartId).carts;
          }
        }
      });
    },
    splitMoney (money) {
      const arr = String(Number(Number(money).toFixed(2))).split('.');
      if (arr.length === 1) {
        return [arr[0], ''];
      } else {
        return [arr[0], '.' + arr[1]];
      }
    },
    addCart () { // 添加到购物车
      const cart = this.carts.find(cart => cart.uid === this.detail.uid);
      if (cart) {
        cart.cart_amount += 1;
      } else {
        const item = { ...this.detail };
        item.cart_amount = 1;
        this.carts.push(item);
      }
      this.$q.localStorage.set(this.cartId, { shopName: this.detail.shop_name, carts: this.carts });
    },
    showCart () {
      this.$refs.cartDialog.show();
    },
    updateCarts (carts) {
      this.carts = carts;
    }
  },
  computed: {
    cartId () {
      return `${this.detail.shop_id || ''}_carts`;
    },
    totalAmount () {
      return this.carts.reduce((a, b) => a + b.cart_amount, 0);
    }
  },
  watch: {
    modelUid (val) {
      if (val) {
        const path = { path: `/shop/detail/${val}` };
        this.$router.replace(path);
      }
    }
  }
});
</script>
